package com.ruibang.glass.material.service;

import com.alibaba.excel.util.DateUtils;
import com.alibaba.excel.util.StringUtils;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

@Service
public class MaterialOUTNumberGenerator {

    private static final String DATE_FORMAT = "yyyyMMdd";
    private static final int MAX_NUMBER = 9999;
    private static final String NUMBER_FORMAT = "%04d";

    public static String generateNewNumber(String inputNumber) {
        if (StringUtils.isBlank(inputNumber)) {
            return "OUT" + DateUtils.format(new Date(), DATE_FORMAT) + "0001"; // 或者抛出异常等
        }
        // 提取日期和编号
        String datePart = inputNumber.substring(3, 11);
        String numberPart = inputNumber.substring(11);

        // 尝试将编号转换为整数
        int number;
        try {
            number = Integer.parseInt(numberPart);
        } catch (NumberFormatException e) {
            // 如果编号不是数字，则返回原始输入或进行错误处理
            return inputNumber; // 或者抛出异常等
        }

        // 检查编号是否小于最大值
        if (number == MAX_NUMBER) {
            // 获取当前日期并格式化为yyyyMMdd
            SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.US);
            String today = sdf.format(Calendar.getInstance().getTime());

            // 重置编号为0002
            String newNumber = String.format(NUMBER_FORMAT, 1);

            // 构建新的编号字符串
            return "OUT"+ today  + newNumber;
        }else {
            SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.US);
            String today = sdf.format(Calendar.getInstance().getTime());
           Integer newNumber= number+1;
            if (newNumber>0 && newNumber<10){
                return "OUT" + today+ "000" + newNumber.toString();
            }
            if (newNumber>=10 && newNumber<100){
                return "OUT"+ today + "00" + newNumber.toString();
            }
            if (newNumber>=100 && newNumber<1000){
                return "OUT" + today+ "0" + newNumber.toString();
            }
            if (newNumber>=1000 && newNumber<1000){
                return "OUT" + today + newNumber.toString();
            }
        }

        // 如果编号不小于最大值，返回原始输入或进行其他处理
        return "OUT" + DateUtils.format(new Date(), DATE_FORMAT) + "0001"; // 或者抛出异常等
    }

    public static void main(String[] args) {
        String input = "OUT202303020002";
        String newNumber = generateNewNumber(input);
        System.out.println(newNumber); // 应该输出类似 OUT2023xxxx0002 的字符串，其中xxxx是今天的日期
    }
}

